package com.yamibuy.ec.resource.aws;

/**
 * 操作S3
 *
 * @author: damon.li
 * @version: 2021年02月24日 13:45
 */

import cn.hutool.core.img.Img;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.IoUtil;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@Component
public class AwsS3Util {


	@Value("${aws.s3.bucket}")
	private String bucket;

	@Resource
	private AmazonS3 amazonS3;

	/**
	 * 在S3获取图片,无图片返回404
	 *
	 * @param key
	 * @return
	 */
	public BufferedImage getImage(String key) {
		try (
				S3Object s3Object = amazonS3.getObject(bucket, key);
				S3ObjectInputStream in = s3Object.getObjectContent();
		) {
			byte[] bytes = IoUtil.readBytes(in);
			return ImgUtil.read(new ByteArrayInputStream(bytes));
		} catch (AmazonS3Exception e) {
			if (e.getStatusCode() == 404) {
				try (
						S3Object s3Object = amazonS3.getObject(bucket, "404.png");
						S3ObjectInputStream in = s3Object.getObjectContent();
				) {
					byte[] bytes = IoUtil.readBytes(in);
					return ImgUtil.read(new ByteArrayInputStream(bytes));
				} catch (IOException e2) {
					e2.printStackTrace();
				}
			} else {
				throw e;
			}
		} catch (IOException e2) {
			e2.printStackTrace();
		}
		return null;
	}


	/**
	 * 在S3获取图片,无图片返回404
	 *
	 * @param key
	 * @return
	 */
	public byte[] getFile(String key) {
		try {
			try (
					S3Object s3Object = amazonS3.getObject(bucket, key);
					S3ObjectInputStream in = s3Object.getObjectContent();
			) {
				byte[] bytes = IoUtil.readBytes(in);
				return bytes;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return new byte[0];
	}

	public String getImageType(BufferedImage bufferedImage) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		Img.from(bufferedImage).write(out);
		return FileTypeUtil.getType(new ByteArrayInputStream(out.toByteArray()));
	}
}
